package com.magic.zhixin.controller;

import com.github.wxpay.sdk.WXPayConstants;
import com.magic.zhixin.entity.Result;
import com.magic.zhixin.entity.UserInfo;
import com.magic.zhixin.model.TransferType;
import com.magic.zhixin.service.WalletService;
import com.magic.zhixin.weixin.WeixinPayUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Map;

@RestController
@RequestMapping("/api/wallet/")
public class WalletController extends BaseController {
    @Autowired
    private WalletService walletService;
    @Autowired
    private WeixinPayUtil weixinPayUtil;

    @ApiOperation("获取余额")
    @GetMapping("getBalance")
    public Result getBalance() {
        return Result.OkResult(walletService.getBalance(currentUser()));
    }

    @ApiOperation("获取明细")
    @GetMapping("getAllTransferRecord")
    public Result getAllTransferRecord() {
        return walletService.getAllTransferRecord(currentUser());
    }

    @ApiOperation("提现")
    @PostMapping("/withdraw")
    public Result withdraw() {
        try {
            UserInfo userInfo = walletService.getBalance(currentUser());
            if (userInfo.getBalance().compareTo(BigDecimal.ONE) >=0) {
                if (userInfo.getBalance().compareTo(new BigDecimal(1000)) >=0) {
                    Map respMap = walletService.transfer(userInfo.getId(), weixinPayUtil.generateSn(), new BigDecimal(1000), TransferType.BALANCE_WITHDRAW);
                    if (respMap.get("result_code").equals(WXPayConstants.FAIL) || respMap.get("return_code").equals(WXPayConstants.FAIL)) {
                        return Result.FailedResult("提现失败");
                    }
                } else {
                    Map respMap = walletService.transfer(userInfo.getId(), weixinPayUtil.generateSn(), userInfo.getBalance(), TransferType.BALANCE_WITHDRAW);
                    if (respMap.get("result_code").equals(WXPayConstants.FAIL) || respMap.get("return_code").equals(WXPayConstants.FAIL)) {
                        return Result.FailedResult("提现失败");
                    }
                }
                return Result.OkResult(null);
            } else {
                return Result.FailedResult("钱包中没有足够的余额");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.FailedResult(e.getMessage());
        }
    }

}
